package com.lekang.system.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.lekang.common.annotation.Log;
import com.lekang.common.core.controller.BaseController;
import com.lekang.common.core.domain.AjaxResult;
import com.lekang.common.enums.BusinessType;
import com.lekang.system.domain.Message;
import com.lekang.system.service.IMessageService;
import com.lekang.common.utils.poi.ExcelUtil;
import com.lekang.common.core.page.TableDataInfo;

/**
 * 消息通知Controller
 * 
 * @author 王驰浩
 * @date 2025-10-16
 */
@RestController
@RequestMapping("/system/messagecenter")
public class MessageController extends BaseController
{
    @Autowired
    private IMessageService messageService;

    /**
     * 查询消息通知列表
     */
    @PreAuthorize("@ss.hasPermi('system:messagecenter:list')")
    @GetMapping("/list")
    public TableDataInfo list(Message message)
    {
        startPage();
        List<Message> list = messageService.selectMessageList(message);
        return getDataTable(list);
    }

    /**
     * 导出消息通知列表
     */
    @PreAuthorize("@ss.hasPermi('system:messagecenter:export')")
    @Log(title = "消息通知", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Message message)
    {
        List<Message> list = messageService.selectMessageList(message);
        ExcelUtil<Message> util = new ExcelUtil<Message>(Message.class);
        util.exportExcel(response, list, "消息通知数据");
    }

    /**
     * 获取消息通知详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:messagecenter:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(messageService.selectMessageById(id));
    }

    /**
     * 新增消息通知
     */
    @PreAuthorize("@ss.hasPermi('system:messagecenter:add')")
    @Log(title = "消息通知", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Message message)
    {
        return toAjax(messageService.insertMessage(message));
    }

    /**
     * 修改消息通知
     */
    @PreAuthorize("@ss.hasPermi('system:messagecenter:edit')")
    @Log(title = "消息通知", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Message message)
    {
        return toAjax(messageService.updateMessage(message));
    }

    /**
     * 删除消息通知
     */
    @PreAuthorize("@ss.hasPermi('system:messagecenter:remove')")
    @Log(title = "消息通知", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(messageService.deleteMessageByIds(ids));
    }

    /**
     * 创建退住申请通知消息
     */
    @PostMapping("/createCheckoutNotification")
    public AjaxResult createCheckoutNotification(@RequestBody java.util.Map<String, Object> params)
    {
        try {
            System.out.println("=== 创建退住申请通知消息 ===");
            
            Long applicationId = Long.valueOf(params.get("applicationId").toString());
            String elderlyName = params.get("elderlyName") != null ? params.get("elderlyName").toString() : "未知老人";
            
            System.out.println("申请ID: " + applicationId);
            System.out.println("老人姓名: " + elderlyName);
            
            // 创建消息对象
            Message message = new Message();
            message.setTitle("通知" + applicationId); // 消息标题：通知 + 主键
            message.setContent("有一个退住申请待处理"); // 消息内容
            message.setMessageType("协同工作"); // 消息类型
            message.setReceiverId(1L); // 接收人ID（这里设置为1，可以根据实际需求调整）
            message.setStatus(0L); // 状态：0=未读，1=已读
            message.setCreateTime(java.util.Calendar.getInstance().getTime()); // 创建时间
            
            System.out.println("创建的消息对象: " + message);
            
            // 插入消息
            int result = messageService.insertMessage(message);
            
            if (result > 0) {
                System.out.println("✅ 退住申请通知消息创建成功！");
                
                // 构建返回数据
                java.util.Map<String, Object> responseData = new java.util.HashMap<>();
                responseData.put("messageId", message.getId());
                responseData.put("title", message.getTitle());
                responseData.put("content", message.getContent());
                responseData.put("messageType", message.getMessageType());
                responseData.put("status", message.getStatus());
                responseData.put("createTime", message.getCreateTime());
                
                return success(responseData);
            } else {
                System.out.println("❌ 退住申请通知消息创建失败");
                return error("退住申请通知消息创建失败");
            }
            
        } catch (Exception e) {
            System.out.println("创建退住申请通知消息异常: " + e.getMessage());
            e.printStackTrace();
            return error("创建退住申请通知消息失败：" + e.getMessage());
        }
    }

    /**
     * 获取未读消息数量
     */
    @GetMapping("/unreadCount")
    public AjaxResult getUnreadCount()
    {
        try {
            System.out.println("=== 获取未读消息数量 ===");
            
            // 查询未读消息数量（status = 0）
            Message queryMessage = new Message();
            queryMessage.setStatus(0L); // 未读状态
            java.util.List<Message> unreadMessages = messageService.selectMessageList(queryMessage);
            
            int unreadCount = unreadMessages != null ? unreadMessages.size() : 0;
            
            System.out.println("未读消息数量: " + unreadCount);
            
            // 构建返回数据
            java.util.Map<String, Object> responseData = new java.util.HashMap<>();
            responseData.put("unreadCount", unreadCount);
            
            return success(responseData);
            
        } catch (Exception e) {
            System.out.println("获取未读消息数量异常: " + e.getMessage());
            e.printStackTrace();
            return error("获取未读消息数量失败：" + e.getMessage());
        }
    }
}
